<template>
  <div class="app-content-wrap" :style="'minHeight:' + gHeight + 'px;'">
    <div class="g-content-title">事件上报</div>
    <el-form :rules="rules" ref="uploadForm" :model="form" label-width="80px" size="small">
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="所属" prop="deptId">
            <areaSelect :selectModel="form.deptId" :areaIds="areaIds" @onAreaChange="onAreaChange" hideThird="true"></areaSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="选择场景" prop="moduleId">
            <sceneSelect :selectModel="form.moduleId" :modTypes="modTypes" @onSceneChange="onSceneChange" :deptId="form.deptId"></sceneSelect>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="24">
          <el-form-item label="选择图片">
            <el-col :span="21" class="upload-box">
              <el-input placeholder="选择图片" type="text" v-model="form.uploadUrl" class="input1"></el-input>
              <input type="file" ref="uploadFileInput" multiple="multiple" class="file" @change="handleExceed"/>
            </el-col>
            <el-col :span="3">
              <el-button class="el-button el-button--primary el-button--small el-col-24" :disabled="uploadState" @click.native="handleUpload">上&nbsp;&nbsp;&nbsp;&nbsp;传</el-button>
            </el-col>
          </el-form-item>
          <el-form-item label="图片展示" v-show="imgLoadShow">
            <el-col :span="20" class="img-box">
              <div class="img-item" v-for="(item,index) in imgData.result" :key="index" @click="imgShowEvent(item)">
                <img :src="item.imgUrl" alt="">
              </div>
            </el-col>
            <el-col :span="4">
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15" class="input_gps">
        <el-col :span="24">
          <el-col :span="6">
            <el-form-item prop="lng" label="位置">
              <el-input v-model="form.lng"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="item-inline" prop="lat">
              <el-input v-model="form.lat"></el-input>
            </el-form-item>
          </el-col>
          <el-col class="item-inline-left" :span="2">
            <el-button type="text" icon="el-icon-location" @click="showMap">选择地图位置</el-button>
          </el-col>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col class="input_address">
          <el-col :span="12">
            <el-form-item label="地址" prop="eventContent">
              <el-input type="text" v-model="form.eventContent" placeholder="请输入地址"></el-input>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col>
          <el-form-item>
            <el-col>
              <el-button type="primary" size="small" @click="onSubmit">提交</el-button>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog top="0" custom-class="pic-popup" :visible.sync="mapVisible">
      <mapSelect :LngLat="lngLat" :MapClick="mapClick"></mapSelect>
    </el-dialog>
  </div>
</template>
<script>
import axios from 'axios/index'
import base from '../../assets/scripts/base/base'
import areaSelect from '../../components/common/select/area'
import sceneSelect from '../../components/common/select/scene'
import mapSelect from '../../components/common/ui/mapSelect'

export default {
  name: 'eventUpload',
  components: {
    areaSelect,
    sceneSelect,
    mapSelect
  },
  data () {
    // 自定义校验规则
    // 子所属验证
    let validateDeptId = (rule, value, callback) => {
      if (this.areaIds.areaId1 && this.areaIds.areaId1 === this.areaIds.areaId2) {
        callback(new Error('请选择子所属'))
      } else {
        callback()
      }
    }
    // 子场景验证
    let validateModuleId = (rule, value, callback) => {
      if (this.modTypes.modType1 && this.modTypes.modType1 === this.modTypes.modType2) {
        callback(new Error('请选择子场景'))
      } else {
        callback()
      }
    }

    return {
      gHeight: this.$store.state.gHeight,
      name: '',
      areaIds: {
        areaId1: '', // 所属1级
        areaId2: '', // 所属2级
        areaId3: '' // 所属3级
      },
      modTypes: {
        modType1: '', // 场景分类
        modType2: '' // 场景子分类
      },
      form: {
        deptId: '', // 所属
        eventId: '', // 事件编号//aereID + eventTime
        moduleId: '', // 场景类型
        eventState: '', // 处理状态
        lng: '',
        lat: '',
        uploadUrl: '',
        eventContent: '', // 事件内容
        eventTime: '',
        eventImage: '',
        // submitPerson: 1, // 登录人
        equipmentId: '',
        eventVideo: 0,
        subType: 2 // 提交类型 固定传 2手动
      },
      rules: {
        deptId: [
          { required: true, message: '所属不能为空', trigger: ['blur'] },
          { validator: validateDeptId, trigger: 'blur' }
        ],
        moduleId: [
          { required: true, message: '场景不能为空', trigger: ['blur'] },
          { validator: validateModuleId, trigger: 'blur' }
        ],
        lng: [
          { required: true, message: '经度不能为空', trigger: ['blur'] }
        ],
        lat: [
          { required: true, message: '纬度不能为空', trigger: ['blur'] }
        ],
        eventContent: [
          { required: true, message: '地址不能为空', trigger: ['blur'] }
        ]
      },
      uploadState: true, // 上传图片是否开启
      mapVisible: false, // 地图是否显示
      mapClick: true, // 地图标注点是否可切换
      lngLat: {}, // 地图标注点的位置
      uploadNum: 0, // 上传图片的最大数量
      nums: 0, // 上传图片张数
      uploadArr: [], // 上传图片的状态
      imgData: {
        result: [],
        code: 0
      }, // 图片展示数据
      uploadFileObj: '', // 上传图片对象
      imgLoadShow: false // 上传图片展示状态
    }
  },
  methods: {
    handleExceed (e) {
      let that = this
      let file = e.target.files
      that.uploadFileObj = file
      let urls = ''
      this.nums = 0
      this.uploadArr = []
      this.imgData.result = []
      if (file.length === 0) {
        this.$message.error('请选择的图片')
      } else if (file.length > this.uploadNum) {
        this.$message.error('上传的图片不能查过' + this.uploadNum + '张')
      } else {
        for (let i = 0; i < file.length; i++) {
          let _name = file[i].name
          if (_name !== '') {
            let ext = _name.slice(_name.lastIndexOf('.') + 1).toLowerCase()
            if (
              ext === 'png' ||
                ext === 'jpg' ||
                ext === 'jpeg' ||
                ext === 'gif'
            ) {
              urls += _name + ','
              that.uploadState = false
              that.imgLoadShow = false
            } else {
              that.$message.error('文件格式错误！')
            }
          }
        }
        urls = urls.substring(0, urls.length - 1)
        that.form.uploadUrl = urls
      }
    },
    handleUpload () {
      let that = this
      if (that.uploadState) {
        return
      }
      if (that.uploadFileObj.length) {
        for (let i = 0; i < that.uploadFileObj.length; i++) {
          let name = that.uploadFileObj[i].name
          let ext = name.slice(name.lastIndexOf('.') + 1).toLowerCase()
          if (ext === 'png' || ext === 'jpg' || ext === 'gif') {
            if (
              typeof that.uploadFileObj[i] === 'undefined' ||
                that.uploadFileObj[i].size <= 0
            ) {
              that.$message.error('请选择图片！')
              return
            } else {
              that.imgUploadFun(that.uploadFileObj[i])
            }
          } else {
            that.$message.error('文件格式错误！')
          }
        }
      } else {
        that.$message.error('请选择图片！')
      }
    },
    imgUploadFun (fileObj) {
      let that = this
      let param = new FormData()
      param.append('action', 'UploadVMKImagePath')
      param.append('multipartFile', fileObj)
      let url = this.$base.getUrl('imgUpload')
      let params = {
        url: url,
        data: param
      }
      that.$store.dispatch('postUploadForm', params).then(res => {
        if (res.code === 0) {
          let obj = {
            imgUrl: res.data.url
          }
          that.imgData.result.push(obj)
          that.uploadArr.push(true)
          that.nums = 0
          for (let j = 0; j < that.uploadArr.length; j++) {
            if (that.uploadArr[j]) {
              that.nums += 1
            }
          }
          if (that.uploadFileObj.length === that.nums) {
            that.uploadState = false
            that.imgLoadShow = true
            that.$message.success('图片上传成功！')
          }
        }
      })
    },
    getUploadNum () {
      let url = this.$base.getUrl('UploadNum')
      let params = {
        url: url
      }
      this.$store.dispatch('getForm', params).then(res => {
        this.uploadNum = res === undefined ? 3 : res
      })
    },
    imgShowEvent (item) {
      // let that = this;
      // that.base.popup({
      //   w: 500,
      //   h: 500,
      //   content: '<img width="500" height="500" :src="' + item.imgUrl + '"/>'
      // });
    },
    onSubmit () {
      let that = this
      let Base = base()
      let loadingOpts = {
        lock: true,
        text: '拼命加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      }

      // if (this.modTypes.modType1 && this.modTypes.modType1 === this.modTypes.modType2) {
      //   this.$message({
      //     type: 'warning',
      //     message: '请选择场景子分类'
      //   })
      //   return
      // }

      let myDate = new Date()
      let myUpdateTime = that.$base.dateToString(myDate) // 获取当前时间  yyyy-mm-dd hh:mm:ss
      let regGetNum = /\d+/g
      let getTimeNum = myUpdateTime.match(regGetNum).join('')
      let eventId = that.form.deptId + getTimeNum
      let url = that.$base.getUrl('eventInsert')
      let data = {
        areaId: that.form.deptId,
        eventId: eventId, // aereID + eventTime
        moduleId: that.form.moduleId,
        eventState: 0, // 处理状态 固定传 0待处理
        gpsIng: that.form.lng,
        gpsLat: that.form.lat,
        eventTime: myUpdateTime,
        eventContent: that.form.eventContent,
        eventImage: JSON.stringify(that.imgData),
        submitPerson: 1, // 登录人
        equipmentId: '',
        eventVideo: 0,
        subType: 2 // 提交类型 固定传 2手动
      }

      // uploadForm
      this.$refs['uploadForm'].validate((valid) => {
        if (valid) {
          let loading = that.$loading(loadingOpts)
          axios.post(url, data, {
            headers: {
              token: Base.getSessionStorage('token')
            }
          }).then(function (res) {
            loading.close()
            if (res.data.code === 403) {
              that.$alert('登录信息失效，请重新登录')
              Base.setSessionStorage('token', '')
              that.commit('changeLoginShow', true)
              return
            }
            if (res.data && res.data.code === 0) {
              that.$message({
                type: 'success',
                message: '事件上报成功！'
              })
              that.$refs['uploadForm'].resetFields()
              that.form.deptId = ''
              that.areaIds = {
                areaId1: '', // 所属1级
                areaId2: '', // 所属2级
                areaId3: '' // 所属3级
              }
            }
            if (res.data.code === 500) {
              that.$message({
                type: 'warning',
                message: res.data.msg
              })
            }
          })
        } else {
          return false
        }
      })
    },
    showMap () {
      if (!this.form.deptId) {
        this.$message({
          type: 'warning',
          message: '请选择特定小区'
        })
        return
      }

      let _this = this
      let url = this.$base.getUrl('getDeptById')
      let params = {
        url: url,
        data: {
          deptId: _this.form.deptId
        }
      }
      _this.lngLat = {}
      this.$store.dispatch('getForm', params).then(res => {
        this.form.lng = res.gpsLng
        this.form.lat = res.gpsLat
        _this.lngLat = {
          lng: res.gpsLng,
          lat: res.gpsLat
        }
        _this.mapVisible = true
        _this.$store.commit('setPointPopShow', true)
      })
    },
    // 所属变化时
    onAreaChange (val) {
      this.form.deptId = val
    },
    onSceneChange (val) {
      this.form.moduleId = val
    }
  },
  mounted: function () {
    this.$nextTick(function () {
      this.getUploadNum()
    })
  },
  computed: {
    pointData () {
      return this.$store.state.event.pointData
    },
    pointPopShow () {
      return this.$store.state.event.pointPopShow
    }
  },
  watch: {
    pointData: {
      handler (curVal) {
        this.form.lng = curVal.lng
        this.form.lat = curVal.lat
      },
      deep: true
    },
    pointPopShow: {
      handler (curVal) {
        this.mapVisible = curVal
      },
      deep: true
    }
  }
}
</script>
<style scoped>
  .upload-box {
    position: relative;
  }

  .upload-box .file {
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    cursor: pointer;
    width: 380px;
    height: 33px;
  }

  .el-dialog__wrapper >>> .pic-popup {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: auto;
    margin: 0;
  }

  .el-dialog__wrapper >>> .el-dialog__body {
    padding: 20px;
  }

  .el-dialog__wrapper >>> .el-dialog__header {
    padding: 10px 20px 10px;
  }

  .el-dialog__wrapper >>> .el-dialog__headerbtn {
    top: 10px;
  }

  .img-box {
    height: 100px;
  }

  .img-box .img-item {
    display: block;
    float: left;
    height: 100px;
    width: 100px;
    margin-right: 10px;
  }

  .img-box .img-item img {
    height: 100px;
    width: 100px;
  }

  .item-inline >>> .el-form-item__content {
    /*margin-left: 0!important;*/
    transform: translate(-80px, 0);
  }

  .item-inline-left {
    transform: translate(-80px, 0);
  }

  .app-content-wrap >>> .el-form-item--small .el-form-item__error {
    padding-left: 10px;
  }

  .input_gps >>> .el-form-item__error, .input_address >>> .el-form-item__error{
    margin-left: -10px;
  }

</style>
